package com.example.service.impl;

import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.PurchaseDTO;
import com.example.entity.PurchaseRecord;
import com.example.entity.StockRecord;
import com.example.entity.SupplyProduct;
import com.example.entity.StoreProduct;
import com.example.entity.UserBalance;
import com.example.mapper.PurchaseRecordMapper;
import com.example.mapper.StockRecordMapper;
import com.example.mapper.SupplyProductMapper;
import com.example.mapper.StoreProductMapper;
import com.example.mapper.UserBalanceMapper;
import com.example.service.PurchaseService;
import com.example.util.JwtUserUtil;
import com.example.vo.PurchaseRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
public class PurchaseServiceImpl implements PurchaseService {
    
    @Autowired
    private PurchaseRecordMapper purchaseRecordMapper;
    
    @Autowired
    private SupplyProductMapper supplyProductMapper;
    
    @Autowired
    private StoreProductMapper storeProductMapper;
    
    @Autowired
    private UserBalanceMapper userBalanceMapper;
    
    @Autowired
    private StockRecordMapper stockRecordMapper;
    
    @Autowired
    private JwtUserUtil jwtUserUtil;
    
    @Override
    @Transactional
    public Result<Void> purchaseProduct(PurchaseDTO purchaseDTO) {
        try {
            // 获取当前用户ID
            Long userId = jwtUserUtil.getCurrentUserIdFromContext();
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            // 验证购买数量
            if (purchaseDTO.getPurchaseQuantity() == null || purchaseDTO.getPurchaseQuantity() <= 0) {
                return Result.error("购买数量必须大于0");
            }
            
            // 查询店长商品信息
            StoreProduct storeProduct = storeProductMapper.selectById(purchaseDTO.getProductId());
            if (storeProduct == null) {
                return Result.error("商品不存在");
            }
            
            // 检查商品是否上架
            if (storeProduct.getStatus() != 1) {
                return Result.error("商品已下架，无法购买");
            }
            
            // 检查库存
            if (storeProduct.getCurrentStock() < purchaseDTO.getPurchaseQuantity()) {
                return Result.error("商品库存不足，当前库存：" + storeProduct.getCurrentStock());
            }
            
            // 计算总金额（使用店长设置的销售价格）
            BigDecimal totalAmount = storeProduct.getSellingPrice().multiply(new BigDecimal(purchaseDTO.getPurchaseQuantity()));
            
            // 查询用户余额
            UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
            if (userBalance == null) {
                return Result.error("用户余额信息不存在，请先初始化余额");
            }
            
            // 检查余额是否充足
            if (userBalance.getBalance().compareTo(totalAmount) < 0) {
                return Result.error("余额不足，当前余额：" + userBalance.getBalance() + "，需要：" + totalAmount);
            }
            
            // 扣减用户余额
            userBalance.setBalance(userBalance.getBalance().subtract(totalAmount));
            userBalance.setTotalConsume(userBalance.getTotalConsume().add(totalAmount));
            userBalance.setUpdateTime(LocalDateTime.now());
            userBalanceMapper.updateById(userBalance);
            
            // 扣减店长商品库存
            int beforeStock = storeProduct.getCurrentStock();
            int newStock = beforeStock - purchaseDTO.getPurchaseQuantity();
            storeProductMapper.updateStock(storeProduct.getId(), newStock);
            
            // 创建出库记录（用户购买导致的出库）
            createStockOutRecord(storeProduct, purchaseDTO.getPurchaseQuantity(), 
                beforeStock, newStock, "用户购买出库", storeProduct.getStoreManagerId());
            
            // 创建购买记录
            PurchaseRecord purchaseRecord = new PurchaseRecord();
            purchaseRecord.setUserId(userId);
            purchaseRecord.setProductId(storeProduct.getId());
            purchaseRecord.setProductName(storeProduct.getProductName());
            purchaseRecord.setProductCode(storeProduct.getProductCode());
            purchaseRecord.setPurchaseQuantity(purchaseDTO.getPurchaseQuantity());
            purchaseRecord.setUnitPrice(storeProduct.getSellingPrice());
            purchaseRecord.setTotalAmount(totalAmount);
            purchaseRecord.setPurchaseStatus(1); // 已完成
            purchaseRecord.setRemark(purchaseDTO.getRemark());
            purchaseRecord.setCreateTime(LocalDateTime.now());
            purchaseRecord.setUpdateTime(LocalDateTime.now());
            purchaseRecord.setDeleted(0);
            
            int result = purchaseRecordMapper.insert(purchaseRecord);
            if (result > 0) {
                log.info("用户购买店长商品成功，用户ID: {}, 店长商品ID: {}, 数量: {}, 总金额: {}", 
                        userId, storeProduct.getId(), purchaseDTO.getPurchaseQuantity(), totalAmount);
                return Result.success();
            } else {
                return Result.error("购买失败");
            }
        } catch (Exception e) {
            log.error("购买商品失败", e);
            return Result.error("购买商品失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<List<PurchaseRecordVO>> getMyPurchaseRecords() {
        try {
            Long userId = jwtUserUtil.getCurrentUserIdFromContext();
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            List<PurchaseRecordVO> records = purchaseRecordMapper.selectByUserId(userId);
            return Result.success(records);
        } catch (Exception e) {
            log.error("获取购买记录失败", e);
            return Result.error("获取购买记录失败");
        }
    }
    
    @Override
    public Result<PageResult<PurchaseRecordVO>> getMyPurchasePage(int page, int size, String keyword) {
        try {
            Long userId = jwtUserUtil.getCurrentUserIdFromContext();
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            int offset = (page - 1) * size;
            List<PurchaseRecordVO> records = purchaseRecordMapper.selectUserPurchasePage(userId, offset, size, keyword);
            long total = purchaseRecordMapper.selectUserPurchaseCount(userId, keyword);
            
            PageResult<PurchaseRecordVO> pageResult = new PageResult<>();
            pageResult.setRecords(records);
            pageResult.setTotal(total);
            pageResult.setCurrent(page);
            pageResult.setSize(size);
            pageResult.setPages((int) Math.ceil((double) total / size));
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询购买记录失败", e);
            return Result.error("分页查询购买记录失败");
        }
    }
    
    @Override
    public Result<PageResult<PurchaseRecordVO>> getAllPurchasePage(int page, int size, String keyword) {
        try {
            int offset = (page - 1) * size;
            List<PurchaseRecordVO> records = purchaseRecordMapper.selectAllPurchasePage(offset, size, keyword);
            long total = purchaseRecordMapper.selectAllPurchaseCount(keyword);
            
            PageResult<PurchaseRecordVO> pageResult = new PageResult<>();
            pageResult.setRecords(records);
            pageResult.setTotal(total);
            pageResult.setCurrent(page);
            pageResult.setSize(size);
            pageResult.setPages((int) Math.ceil((double) total / size));
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询所有购买记录失败", e);
            return Result.error("分页查询所有购买记录失败");
        }
    }
    
    @Override
    public Result<PurchaseRecordVO> getPurchaseRecordById(Long id) {
        try {
            PurchaseRecordVO record = purchaseRecordMapper.selectVOById(id);
            if (record == null) {
                return Result.error("购买记录不存在");
            }
            return Result.success(record);
        } catch (Exception e) {
            log.error("查询购买记录详情失败，ID: {}", id, e);
            return Result.error("查询购买记录详情失败");
        }
    }
    
    @Override
    public Result<List<PurchaseRecordVO>> getPurchaseRecordsByProductId(Long productId) {
        try {
            List<PurchaseRecordVO> records = purchaseRecordMapper.selectByProductId(productId);
            return Result.success(records);
        } catch (Exception e) {
            log.error("根据商品ID查询购买记录失败，商品ID: {}", productId, e);
            return Result.error("根据商品ID查询购买记录失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> cancelPurchaseRecord(Long id) {
        try {
            // 查询购买记录
            PurchaseRecord record = purchaseRecordMapper.selectById(id);
            if (record == null) {
                return Result.error("购买记录不存在");
            }
            
            // 检查是否是当前用户的记录
            Long userId = jwtUserUtil.getCurrentUserIdFromContext();
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            if (!record.getUserId().equals(userId)) {
                return Result.error("无权限取消此购买记录");
            }
            
            // 检查记录状态
            if (record.getPurchaseStatus() != 1) {
                return Result.error("只能取消已完成的购买记录");
            }
            
            // 更新记录状态为已取消
            record.setPurchaseStatus(2);
            record.setUpdateTime(LocalDateTime.now());
            purchaseRecordMapper.updateById(record);
            
            // 退还用户余额
            UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
            if (userBalance != null) {
                userBalance.setBalance(userBalance.getBalance().add(record.getTotalAmount()));
                userBalance.setTotalConsume(userBalance.getTotalConsume().subtract(record.getTotalAmount()));
                userBalance.setUpdateTime(LocalDateTime.now());
                userBalanceMapper.updateById(userBalance);
            }
            
            // 恢复店长商品库存
            StoreProduct storeProduct = storeProductMapper.selectById(record.getProductId());
            if (storeProduct != null) {
                int beforeStock = storeProduct.getCurrentStock();
                int newStock = beforeStock + record.getPurchaseQuantity();
                storeProductMapper.updateStock(storeProduct.getId(), newStock);
                
                // 创建入库记录（取消购买导致的入库）
                createStockInRecord(storeProduct, record.getPurchaseQuantity(), 
                    beforeStock, newStock, "取消购买入库", storeProduct.getStoreManagerId());
            }
            
            log.info("取消购买记录成功，记录ID: {}", id);
            return Result.success();
        } catch (Exception e) {
            log.error("取消购买记录失败，记录ID: {}", id, e);
            return Result.error("取消购买记录失败");
        }
    }
    
    /**
     * 创建出库记录
     */
    private void createStockOutRecord(StoreProduct storeProduct, Integer quantity, 
                                     Integer beforeStock, Integer afterStock, 
                                     String remark, Long operatorId) {
        try {
            // 查询供货商品信息
            SupplyProduct supplyProduct = supplyProductMapper.selectById(storeProduct.getSupplyProductId());
            if (supplyProduct == null) {
                log.warn("创建出库记录失败：供货商品不存在，店长商品ID: {}", storeProduct.getId());
                return;
            }
            
            StockRecord stockRecord = new StockRecord();
            stockRecord.setRecordNo(generateStockRecordNo());
            stockRecord.setProductId(supplyProduct.getId()); // 使用供货商品ID
            stockRecord.setProductName(supplyProduct.getProductName());
            stockRecord.setProductCode(supplyProduct.getProductCode());
            stockRecord.setRecordType("OUT"); // 出库
            stockRecord.setQuantity(quantity);
            stockRecord.setBeforeStock(beforeStock);
            stockRecord.setAfterStock(afterStock);
            stockRecord.setOperatorId(operatorId);
            stockRecord.setOperatorName("系统自动(店长出库)"); // 标识为店长出库，使其显示在店长端
            stockRecord.setRemark(remark);
            stockRecord.setCreateTime(LocalDateTime.now());
            stockRecord.setUpdateTime(LocalDateTime.now());
            stockRecord.setDeleted(0);
            
            int result = stockRecordMapper.insert(stockRecord);
            if (result > 0) {
                log.info("自动创建出库记录成功，记录编号: {}, 商品: {}, 数量: {}", 
                    stockRecord.getRecordNo(), supplyProduct.getProductName(), quantity);
            } else {
                log.warn("自动创建出库记录失败，商品: {}, 数量: {}", 
                    supplyProduct.getProductName(), quantity);
            }
        } catch (Exception e) {
            log.error("创建出库记录异常", e);
        }
    }
    
    /**
     * 创建入库记录
     */
    private void createStockInRecord(StoreProduct storeProduct, Integer quantity, 
                                    Integer beforeStock, Integer afterStock, 
                                    String remark, Long operatorId) {
        try {
            // 查询供货商品信息
            SupplyProduct supplyProduct = supplyProductMapper.selectById(storeProduct.getSupplyProductId());
            if (supplyProduct == null) {
                log.warn("创建入库记录失败：供货商品不存在，店长商品ID: {}", storeProduct.getId());
                return;
            }
            
            StockRecord stockRecord = new StockRecord();
            stockRecord.setRecordNo(generateStockRecordNo());
            stockRecord.setProductId(supplyProduct.getId()); // 使用供货商品ID
            stockRecord.setProductName(supplyProduct.getProductName());
            stockRecord.setProductCode(supplyProduct.getProductCode());
            stockRecord.setRecordType("IN"); // 入库
            stockRecord.setQuantity(quantity);
            stockRecord.setBeforeStock(beforeStock);
            stockRecord.setAfterStock(afterStock);
            stockRecord.setOperatorId(operatorId);
            stockRecord.setOperatorName("系统自动(店长入库)"); // 标识为店长入库，使其显示在店长端
            stockRecord.setRemark(remark);
            stockRecord.setCreateTime(LocalDateTime.now());
            stockRecord.setUpdateTime(LocalDateTime.now());
            stockRecord.setDeleted(0);
            
            int result = stockRecordMapper.insert(stockRecord);
            if (result > 0) {
                log.info("自动创建入库记录成功，记录编号: {}, 商品: {}, 数量: {}", 
                    stockRecord.getRecordNo(), supplyProduct.getProductName(), quantity);
            } else {
                log.warn("自动创建入库记录失败，商品: {}, 数量: {}", 
                    supplyProduct.getProductName(), quantity);
            }
        } catch (Exception e) {
            log.error("创建入库记录异常", e);
        }
    }
    
    /**
     * 生成库存记录编号
     */
    private String generateStockRecordNo() {
        return "SR" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + 
               String.format("%03d", (int)(Math.random() * 1000));
    }
} 